package com.cheng.spider.request;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpRequestBase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public abstract class AbstractRequester implements Requester, Configurable {

    private static final Logger LOGGER = LoggerFactory.getLogger(AbstractRequester.class);

    private HttpClient httpClient = SingletonHttpClientBuilder.build();

    HttpRequestBase request = null;

    public HttpTransaction execute(String url) {
        LOGGER.info("正在访问Url：" + url);
        this.request = generateRequest(url);
        HttpResponse response = null;
        configRequest(request);
        try {
            response = this.httpClient.execute(request);
        } catch (IOException e) {
            LOGGER.error("访问Url无响应：" + url);
            throw new RuntimeException("访问Url无响应：" + url, e);
        }

        return new HttpTransaction(request, response);
    }

    protected abstract HttpRequestBase generateRequest(String url);

    public HttpRequestBase getRequest() {
        return request;
    }
}
